// LHOAG 创作
document.addEventListener('DOMContentLoaded', () => {
    const ROWS = 9;
    const COLS = 9;
    const TYPES = 4;
    const TILE_SIZE = 62;
    let selectedTile = null;
    let board = [];
    let score = 0;
    let isAnimating = false;
    let tileElements = [];

    function initGame() {
        const gameBoard = document.getElementById('game-board');
        gameBoard.innerHTML = '';
        tileElements = [];
        
        // 生成有效初始棋盘
        do {
            for (let i = 0; i < ROWS; i++) {
                board[i] = [];
                for (let j = 0; j < COLS; j++) {
                    board[i][j] = Math.floor(Math.random() * TYPES) + 1;
                }
            }
        } while (checkMatches(true));
        
        renderBoard();
        updateScore(0);
    }

    function renderBoard() {
        const gameBoard = document.getElementById('game-board');
        gameBoard.innerHTML = '';
        tileElements = [];
        
        for (let i = 0; i < ROWS; i++) {
            tileElements[i] = [];
            for (let j = 0; j < COLS; j++) {
                const tile = createTile(i, j);
                gameBoard.appendChild(tile);
                tileElements[i][j] = tile;
            }
        }
    }

    function createTile(row, col) {
        const tile = document.createElement('div');
        tile.className = 'tile';
        tile.dataset.row = row;
        tile.dataset.col = col;
        tile.style.left = col * TILE_SIZE + 'px';
        tile.style.top = row * TILE_SIZE + 'px';
        tile.style.backgroundImage = `url(pic/${board[row][col]}.jpg)`;
        tile.addEventListener('click', handleTileClick);
        return tile;
    }

    function updateScore(points) {
        score += points;
        document.getElementById('score').textContent = score;
    }

    function handleTileClick(event) {
        if (isAnimating) return;
        
        const row = parseInt(event.target.dataset.row);
        const col = parseInt(event.target.dataset.col);
        if (board[row][col] === 0) return;
        
        if (!selectedTile) {
            selectedTile = { row, col };
            event.target.classList.add('selected');
        } else {
            const isAdjacent = Math.abs(selectedTile.row - row) + Math.abs(selectedTile.col - col) === 1;
            
            if (isAdjacent) {
                isAnimating = true;
                swapTiles(selectedTile, { row, col });
            }
            
            document.querySelector('.selected')?.classList.remove('selected');
            selectedTile = null;
        }
    }

    function swapTiles(first, second) {
        const tileA = tileElements[first.row][first.col];
        const tileB = tileElements[second.row][second.col];
        
        // 视觉交换动画
        tileA.style.zIndex = 2;
        tileB.style.zIndex = 2;
        tileA.style.transform = `translate(${(second.col - first.col) * TILE_SIZE}px, ${(second.row - first.row) * TILE_SIZE}px)`;
        tileB.style.transform = `translate(${(first.col - second.col) * TILE_SIZE}px, ${(first.row - second.row) * TILE_SIZE}px)`;
        
        setTimeout(() => {
            // 实际数据交换
            [board[first.row][first.col], board[second.row][second.col]] = 
            [board[second.row][second.col], board[first.row][first.col]];
            
            // 更新元素引用
            tileElements[first.row][first.col] = tileB;
            tileElements[second.row][second.col] = tileA;
            
            // 更新数据属性
            tileA.dataset.row = second.row;
            tileA.dataset.col = second.col;
            tileB.dataset.row = first.row;
            tileB.dataset.col = first.col;
            
            // 重置样式
            tileA.style.transform = '';
            tileB.style.transform = '';
            tileA.style.zIndex = '';
            tileB.style.zIndex = '';
            
            // 检查匹配
            if (checkMatches()) {
                updateScore(100);
                processMatches();
            } else {
                // 无效交换回滚
                setTimeout(() => {
                    [board[first.row][first.col], board[second.row][second.col]] = 
                    [board[second.row][second.col], board[first.row][first.col]];
                    
                    tileElements[first.row][first.col] = tileA;
                    tileElements[second.row][second.col] = tileB;
                    
                    tileA.dataset.row = first.row;
                    tileA.dataset.col = first.col;
                    tileB.dataset.row = second.row;
                    tileB.dataset.col = second.col;
                    
                    tileA.style.transform = `translate(${(second.col - first.col) * TILE_SIZE}px, ${(second.row - first.row) * TILE_SIZE}px)`;
                    tileB.style.transform = `translate(${(first.col - second.col) * TILE_SIZE}px, ${(first.row - second.row) * TILE_SIZE}px)`;
                    
                    setTimeout(() => {
                        tileA.style.transform = '';
                        tileB.style.transform = '';
                        isAnimating = false;
                    }, 300);
                }, 300);
            }
        }, 300);
    }

    function checkMatches(initialCheck = false) {
        let matches = new Set();
        
        // 横向匹配检测
        for (let i = 0; i < ROWS; i++) {
            for (let j = 0; j < COLS - 2; j++) {
                if (board[i][j] !== 0 &&
                    board[i][j] === board[i][j+1] && 
                    board[i][j] === board[i][j+2]) {
                    let k = j;
                    while (k < COLS && board[i][j] === board[i][k]) {
                        matches.add(`${i},${k}`);
                        k++;
                    }
                }
            }
        }
        
        // 纵向匹配检测
        for (let j = 0; j < COLS; j++) {
            for (let i = 0; i < ROWS - 2; i++) {
                if (board[i][j] !== 0 &&
                    board[i][j] === board[i+1][j] && 
                    board[i][j] === board[i+2][j]) {
                    let k = i;
                    while (k < ROWS && board[i][j] === board[k][j]) {
                        matches.add(`${k},${j}`);
                        k++;
                    }
                }
            }
        }
        
        // LHOAG 创作
        if (!initialCheck && matches.size > 0) {
            matches.forEach(pos => {
                const [x, y] = pos.split(',').map(Number);
                tileElements[x][y].classList.add('matched');
                board[x][y] = 0;
            });
            return true;
        }
        return matches.size > 0;
    }

    function processMatches() {
        // 移除匹配元素
        const matchedTiles = document.querySelectorAll('.tile.matched');
        matchedTiles.forEach(tile => {
            tile.remove();
        });
        
        // 执行下落逻辑
        setTimeout(() => {
            const moves = [];
            
            // 处理每列下落
            for (let j = 0; j < COLS; j++) {
                let writeIndex = ROWS - 1;
                for (let i = ROWS - 1; i >= 0; i--) {
                    if (board[i][j] !== 0) {
                        if (writeIndex !== i) {
                            board[writeIndex][j] = board[i][j];
                            moves.push({
                                from: { row: i, col: j },
                                to: { row: writeIndex, col: j }
                            });
                        }
                        writeIndex--;
                    }
                }
                // 生成新方块
                for (let i = writeIndex; i >= 0; i--) {
                    board[i][j] = Math.floor(Math.random() * TYPES) + 1;
                    moves.push({
                        from: { row: -1, col: j },
                        to: { row: i, col: j }
                    });
                }
            }
            
            // 执行下落动画
            animateMoves(moves);
            
            // 检查连锁反应
            setTimeout(() => {
                if (checkMatches()) {
                    updateScore(50);
                    processMatches();
                } else {
                    isAnimating = false;
                    renderBoard(); // 确保视图完全刷新
                }
            }, 600);
        }, 500);
    }

    function animateMoves(moves) {
        // 创建新元素
        moves.forEach(move => {
            if (move.from.row === -1) {
                const tile = createTile(move.to.row, move.to.col);
                tile.style.top = `${-TILE_SIZE}px`;
                tileElements[move.to.row][move.to.col] = tile;
                document.getElementById('game-board').appendChild(tile);
                setTimeout(() => {
                    tile.style.top = `${move.to.row * TILE_SIZE}px`;
                    tile.classList.add('new');
                }, 10);
            }
        });
        
        // 移动现有元素
        moves.forEach(move => {
            if (move.from.row >= 0) {
                const tile = tileElements[move.from.row][move.from.col];
                tile.dataset.row = move.to.row;
                tile.dataset.col = move.to.col;
                tile.style.top = `${move.to.row * TILE_SIZE}px`;
                tileElements[move.to.row][move.to.col] = tile;
            }
        });
    }

    initGame();
});
